import * as bm from "/js/baseModule.js";
let auiPullToRefresh = require('/js/auiPullToRefresh.js');

export class Module extends bm.baseModule {
    constructor(view) {
        super(view);
        let that = this;
        that._vote_supplier = 0;
        that._me_cnt = 0;
        that._total_cnt = 0;
        this.defaultOption = {
            city: 'mine',
            demand: 'all',
            business: 'all'
        };
        that._moreDamenaVue = new Vue({
            el: $('.get-more-demand')[0],
            data: {
                me_cnt: that._me_cnt,
                total_cnt: that._total_cnt,
            },
        });
        new Vue({
            el: $("#ProjectList-container")[0],
            data: {
                items: globalData.project_list,
                vote_supplier: that._vote_supplier,
                selected_province: globalData.selPos.prov,
            },
            methods: {
                updateTime: function (startTime) {
                    return funs.countTimeGap(startTime)
                },
                callStop: function (phone, event) {
                    event.stopPropagation();    //  阻止事件冒泡
                    // tomato.getVPresenter<FromWPH>(funs.moduleToUrl('m/grab/FromWPH'), (FromWPH) => {
                    //     FromWPH.callPhone(phone);
                    //     tdom.open(FromWPH, tdom.DialogTarget.Blank, {
                    //         size: { width: '90%', height: tomato.DialogSize.Content },
                    //         effect: tdom.DialogEffect.scale,
                    //         masked: true
                    //     });
                    // })
                }
            }
        });
        this._moreLoading = this.find(".downMore");
        this._outerScroller = this.find(".outerScroller");

        if(globalData.entryPage == 'index'){
            funs.removeWelcome();
        }
        let pullRefresh = new auiPullToRefresh({
            container: document.querySelector('.aui-refresh-content'),
            triggerDistance: 100,
            // "pullImage": "../image/pull_refresh.png", //下拉时显示的图片，带旋转
            // "loadingImage": "../images/loading.gif", //加载中的图片
            // "callback": loadingCallback //刷新回调
        }, function (ret) {
            if (ret.status == "success") {
                //刷新回调
                that.loadMore();
                pullRefresh.cancelLoading(); //刷新成功后调用此方法隐藏
            }
        })

        $(document).on('data_update',function () {
            // 特殊处理 台湾省 ， 更新列表
            if (globalData.user.prov == "台湾省") {
                globalData.selected_province.province_id = "台湾省";
                globalData.selected_province.province_name = "台湾省";
                api.getDemandList({"sort_val": ''}, function (data) {
                    globalData.project_list.length = 0;
                    globalData.project_list.push(...data);
                }, function () {
                    // 不处理
                })
            }

            //如果是从“我参与的”链接进入的
            if (globalData.particalList) {
                that.defaultOption = {
                    city: 'all',
                    demand: 'all',
                    business: 'mine'
                };
                that.find('.js-city .choice-val').text('全国');
                that.find('.js-demand .choice-val').text('我参与的');
            }

            //如果是游客/客户，修改默认请求配置
            if (globalData.user.user_type != 100) {
                that.defaultOption = {
                    city: 'all',
                    demand: 'all',
                    business: 'all'
                };
                that.find('.js-city .choice-val').text('全国');
            }
            //如果是从“免费订单”链接进入的
            if (globalData.freeList) {
                that.find('.js-city .choice-val').text('全国');
                that.find('.js-demand .choice-val').text('免费订单');
                that.defaultOption = {
                    city: 'all',
                    demand: 'free',
                    business: 'all'
                };
                // that.loadMore(that.defaultOption);
            }
        });
        //请求头部数据
        that.getTodayCnt();

    }

    /**项目的点击事件 */
    _evt_projectDetail(obj) {
        let id = $(obj).attr('did');
        let pro_info = this.getProjectData(id);
        if (pro_info) {
            globalData.current_demand = pro_info;
            location.hash = 'demand?did='+id;
        }
    }

    /**获取单个项目的详细信息 */
    getProjectData(did){
        for (let a of globalData.project_list) {
            if (a.id == did) {
                return a
            }
        }
    }

    /**获取头部数据：_me_cnt与我相关的需求数量，_total_cnt今天的需求总数 */
    getTodayCnt() {
        let that = this;
        api.getTodayCnt(
            function (json) {
                that._moreDamenaVue.me_cnt = json.me_cnt;
                that._moreDamenaVue.total_cnt = json.total_cnt;
            },
            function (error) {
                if (error.name == '41009002') {
                    //不是工程商
                    window.location.href = '/index.html';
                } else {
                    funs.tip(error.name, error.message, "fail");
                }
            }
        );
    }

    /**加载更多 */
    loadMore(option) {
        let that = this;
        //请求头部数据
        this.getTodayCnt();
        if (this._loadMore) {
            return;
        }
        this._loadMore = true;
        this._moreLoading.removeClass("hide");
        let next = () => {
            this._loadMore = false;
            this._moreLoading.addClass("hide");
            this.find(".promptBar").removeClass('hide');
            this._outerScroller.scrollTop(0);
            setTimeout(() => {
                this.find('.promptBar').addClass('hide');
            }, 3000);
        }
        let plist = globalData.project_list;
        let sort_val;
        if (plist.length == 0) {
            sort_val = "";
        } else {
            sort_val = plist[0].published_at;
        }
        let options = {"sort_val": sort_val};
        //如果有option，则是筛选条件调用的方法；没有则是下拉刷新
        if (option) {
            api.getDemandListDesc(that.defaultOption, {
                succ: function (data) {
                    let newList = data;
                    //替换数据
                    globalData.project_list.length = 0;
                    globalData.project_list.push(...newList);

                    if (newList.length != 0) {
                        that.find(".promptBar").text('项目列表已更新');
                    } else {
                        that.find(".promptBar").text("当前设置下无项目");
                    }

                    // 缓存项目列表
                    let prolist = globalData.project_list;
                    prolist = JSON.stringify(prolist);
                    localStorage.setItem("prolist", prolist);
                    next();
                },
                fail: () => {
                    setTimeout(next, 3000);
                }
            });
        } else {
            $.extend(options, this.defaultOption);
            api.getDemandList(options, {
                succ: function (data) {
                    let newList = data;
                    if (newList.length != 0) {
                        console.log("newList.length=============" + newList.length);
                        that.find(".promptBar").text("更新了" + newList.length + "条新状态");
                        //向前插入数据
                        globalData.project_list.unshift(...newList);
                        setTimeout(next, 1000);
                        // 缓存项目列表
                        let prolist = globalData.project_list;
                        prolist = JSON.stringify(prolist);
                        localStorage.setItem("prolist", prolist);
                    } else {
                        that.find(".promptBar").text("暂无更新");
                        setTimeout(next, 1000);
                    }
                },
                fail: () => {
                    setTimeout(next, 3000);
                }
            });
        }

    }

    //城市选择的结果导入，并刷新列表
    setCity(city) {
        this.defaultOption.city = city;
        this.loadMore(true);
        this.find('.js-city .choice-val').text(city);
    }

    /** ========= 首页项目列表筛选条件-start ===========*/
    _evt_openChoice(obj) {
        // ======= 动画效果 =======
        let icon = $(obj).find('.icon-circle-down');
        let index = $(obj).index('.dropBtn .col-xs-4');
        let choicePane = $('.choice-pane');
        // 为了动画效果的完美，故判断；否则可以toggle简洁的实现的；
        if (icon.hasClass('rotate')) {
            choicePane.slideToggle();
            setTimeout(function () {
                choicePane.find('ul').eq(index).toggle();
            }, 500);

        } else {
            //在已经打开的情况下，切换大选项类
            if ($('.dropBtn').find('.rotate').length > 0) {
                $(obj).siblings().find('span').removeClass('rotate');
                choicePane.find('ul').hide();
                choicePane.find('ul').eq(index).toggle();
            } else {
                choicePane.find('ul').eq(index).toggle();
                choicePane.slideToggle();
            }

        }
        icon.toggleClass('rotate');

    }

    _evt_chooseFilter(obj, hit) {
        //点击后收起筛选框
        let choicePane = $('.choice-pane');
        if (obj == hit) {
            choicePane.slideToggle();
            $('.dropBtn').find('.rotate').removeClass('rotate');
            setTimeout(function () {
                choicePane.find('ul').hide();
            }, 500);
            return
        }
        choicePane.slideToggle();
        $('.dropBtn').find('.rotate').removeClass('rotate');
        let index = $(hit).parent('ul').index('.choice-pane>ul');
        $('.dropBtn').find('.choice-val').eq(index).text($(hit).text().trim().substr(0, 4));
        setTimeout(function () {
            choicePane.find('ul').hide();
        }, 500);

        // 点击了某个筛选条件
        let arr = $(hit).attr('con').split('@');
        // 如果选择了指定城市，则是打开城市选择
        if (arr[1] == 'none') {
            location.hash = 'project/SelProvDemand';
            return
        }
        //如果是游客/客户点击了需要登录的选项
        if (arr[1] == 'mine' && globalData.user.user_type != 100) {
            let type = 1;
            if (globalData.user.user_type == 1) {
                type = 2;
            }
            $(document).trigger('openLoginModal', [false, type]);
            return
        }

        //其他条件则是取到配置项，获取新的list
        let option = {};
        option[arr[0]] = arr[1];
        $.extend(this.defaultOption, option);
        this.loadMore(option);
        console.dir(this.defaultOption, option)
    }
}